<template>
  <div class="procurement-suppliers">
    <!-- 数据管理模式切换 -->
    <el-tabs v-model="viewMode" class="view-mode-tabs">
      <el-tab-pane label="业务模式" name="business">
        <!-- 业务模式内容 -->
        <!-- 页面标题 -->
        <PageHeader 
          title="供应商管理" 
          description="管理采购供应商信息，包括供应商档案、资质审核等"
          icon="OfficeBuilding"
        />
        
        <!-- 搜索和筛选区域 -->
        <el-card class="filter-card" shadow="never">
          <el-form :model="filterForm" label-width="80px" inline>
            <el-form-item label="供应商名称">
              <el-input v-model="filterForm.name" placeholder="请输入供应商名称" />
            </el-form-item>
            <el-form-item label="供应商分类">
              <el-select v-model="filterForm.category" placeholder="请选择分类" clearable>
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装" value="clothing" />
                <el-option label="配件" value="accessories" />
                <el-option label="图书" value="books" />
                <el-option label="软件" value="software" />
              </el-select>
            </el-form-item>
            <el-form-item label="合作状态">
              <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                <el-option label="合作中" value="active" />
                <el-option label="暂停合作" value="suspended" />
                <el-option label="已终止" value="terminated" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 操作按钮区域 -->
        <div class="action-buttons">
          <el-button type="primary" @click="handleAddSupplier">新增供应商</el-button>
          <el-button @click="handleImport">导入供应商</el-button>
          <el-button @click="handleExport">导出供应商</el-button>
        </div>
        
        <!-- 供应商列表 -->
        <el-card class="list-card" shadow="never">
          <el-table :data="supplierList" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="供应商ID" width="80" />
            <el-table-column prop="name" label="供应商名称" min-width="150" />
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="contact" label="联系人" width="100" />
            <el-table-column prop="phone" label="联系电话" width="120" />
            <el-table-column prop="email" label="邮箱" width="150" />
            <el-table-column prop="address" label="地址" min-width="200" />
            <el-table-column prop="status" label="合作状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="合作开始时间" width="160" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="success" link @click="handleView(row)">查看</el-button>
                <el-button type="warning" link @click="handleToggleStatus(row)">
                  {{ row.status === 'active' ? '暂停合作' : '恢复合作' }}
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
        
        <!-- 供应商对话框 -->
        <el-dialog v-model="supplierDialogVisible" :title="dialogTitle" width="600px">
          <el-form :model="supplierForm" label-width="100px" ref="supplierFormRef">
            <el-form-item label="供应商名称" required>
              <el-input v-model="supplierForm.name" />
            </el-form-item>
            <el-form-item label="供应商分类" required>
              <el-select v-model="supplierForm.category" placeholder="请选择分类">
                <el-option label="电子产品" value="electronics" />
                <el-option label="服装" value="clothing" />
                <el-option label="配件" value="accessories" />
                <el-option label="图书" value="books" />
                <el-option label="软件" value="software" />
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" required>
              <el-input v-model="supplierForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" required>
              <el-input v-model="supplierForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="supplierForm.email" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="supplierForm.address" type="textarea" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="supplierForm.remark" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="supplierDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmSupplier">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="数据管理模式" name="data">
        <!-- 数据管理模式内容 -->
        <!-- 页面标题 -->
        <PageHeader 
          title="供应商管理" 
          description="管理您的供应商信息，进行批量导入/导出、数据清洗等数据维护操作"
          icon="OfficeBuilding"
        />
        
        <!-- 添加提示信息 -->
        <div class="data-management-tip" v-if="showDataManagementTip">
          <el-alert
            title="提示：此页面用于批量数据维护。如需进行日常业务操作，请切换到业务模式"
            type="info"
            show-icon
            closable
            @close="handleTipClose"
          >
            <template #default>
              <div class="tip-content">
                <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
                <el-link type="primary" @click="goToProcurementManagement">采购管理 → 供应商管理</el-link>
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 智能洞察 -->
        <SmartInsights 
          v-if="stats && Object.keys(stats).length > 0"
          :insights="smartInsights"
          @action="handleInsightAction"
        />
        
        <!-- 供应商统计 -->
        <SupplierStatsData 
          :stats="stats"
          :loading="loading"
        />
        
        <!-- 功能区域 -->
        <el-card class="function-area" shadow="never">
          <el-row :gutter="20">
            <el-col :span="16">
              <SupplierFilterData 
                :query-params="queryParams"
                @search="handleSearch"
                @reset="handleReset"
              />
            </el-col>
            <el-col :span="8">
              <div class="function-buttons">
                <el-dropdown trigger="click" @command="handleBatchCommand">
                  <el-button class="batch-btn">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="export">导出供应商</el-dropdown-item>
                      <el-dropdown-item command="import">导入供应商</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除供应商</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 供应商表格 -->
        <SupplierTableData
          :suppliers="suppliers"
          :loading="loading"
          :pagination="pagination"
          :selected-suppliers="selectedSuppliers"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @command="handleTableCommand"
        />
        
        <!-- 新增供应商抽屉 -->
        <SupplierOperationDialog
          v-model="addDrawerVisible"
          :editing-supplier="null"
          @submit="createSupplier"
          @close="handleAddDrawerClose"
        />
        
        <!-- 编辑供应商抽屉 -->
        <SupplierOperationDialog
          v-model="editDrawerVisible"
          :editing-supplier="editingSupplier"
          @submit="updateSupplier"
          @close="handleEditDrawerClose"
        />
        
        <!-- 供应商详情抽屉 -->
        <SupplierDetailData
          v-model="detailDrawerVisible"
          :supplier="detailSupplier"
          @edit="handleEditSupplier"
          @close="handleDetailDrawerClose"
        />
        
        <!-- 供应商导入向导 -->
        <SupplierImportWizard
          v-model="importWizardVisible"
          @import-success="handleImportSuccess"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from '@vue/runtime-core'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  OfficeBuilding, Plus, ArrowDown, Upload, Download, Delete 
} from '@element-plus/icons-vue'
import PageHeader from '@/components/layout/PageHeader.vue'

// 使用路由
const router = useRouter()

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 视图模式
const viewMode = ref('business')

// 跳转到采购管理
const goToProcurementManagement = () => {
  router.push('/procurement/suppliers')
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 数据管理模式相关数据
const addDrawerVisible = ref(false)
const editDrawerVisible = ref(false)
const detailDrawerVisible = ref(false)
const importWizardVisible = ref(false)
const detailSupplier = ref<any>(null)
const editingSupplier = ref<any>(null)
const selectedSuppliers = ref<any[]>([])
const smartInsights = ref([])
const suppliers = ref([])
const loading = ref(false)
const stats = ref({
  totalSuppliers: 0,
  activeSuppliers: 0,
  keySuppliers: 0,
  newSuppliers: 0,
  supplierTrend: 0,
  newSupplierTrend: 0,
  activeSupplierTrend: 0,
  keySupplierTrend: 0
})

// 数据管理模式相关方法
const handleInsightAction = (action: string, insight: any) => {
  // 处理智能洞察操作
}

const handleBatchCommand = (command: string) => {
  // 处理批量操作
}

const handleTableCommand = (command: string, row: any) => {
  // 处理表格命令
}

const createSupplier = async (data: any) => {
  // 创建供应商
}

const updateSupplier = async (data: any) => {
  // 更新供应商
}

const handleEditSupplier = (supplier: any) => {
  // 处理编辑供应商
}

const handleImportSuccess = () => {
  // 处理导入成功
}

const handleAddDrawerClose = () => {
  addDrawerVisible.value = false
}

const handleEditDrawerClose = () => {
  editDrawerVisible.value = false
}

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false
}

// 导入数据管理组件
import SmartInsights from '@/components/insights/SmartInsights.vue'
import SupplierStatsData from '@/views/purchase/suppliers-data-components/components/SupplierStats.vue'
import SupplierFilterData from '@/views/purchase/suppliers-data-components/components/SupplierFilter.vue'
import SupplierTableData from '@/views/purchase/suppliers-data-components/components/SupplierTable.vue'
import SupplierDetailData from '@/views/purchase/suppliers-data-components/components/SupplierDetail.vue'
import SupplierImportWizard from '@/views/purchase/suppliers-data-components/components/SupplierImportWizard.vue'
import SupplierOperationDialog from '@/views/purchase/suppliers-data-components/components/SupplierOperationDialog.vue'

// 业务模式相关代码保持不变
interface Supplier {
  id: number
  name: string
  category: string
  contact: string
  phone: string
  email: string
  address: string
  status: 'active' | 'suspended' | 'terminated'
  createdAt: string
  remark: string
}

// 筛选表单
const filterForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态
const supplierList = ref<Supplier[]>([])
const supplierDialogVisible = ref(false)
const dialogTitle = ref('新增供应商')
const isEdit = ref(false)

// 表单引用
const supplierFormRef = ref()

// 表单数据
const supplierForm = reactive({
  id: 0,
  name: '',
  category: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  remark: ''
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'suspended': return 'warning'
    case 'terminated': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active': return '合作中'
    case 'suspended': return '暂停合作'
    case 'terminated': return '已终止'
    default: return '未知'
  }
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', filterForm)
  loadSupplierList()
}

// 重置
const handleReset = () => {
  filterForm.name = ''
  filterForm.category = ''
  filterForm.status = ''
  loadSupplierList()
}

// 加载供应商列表
const loadSupplierList = () => {
  loading.value = true
  // 模拟数据
  setTimeout(() => {
    supplierList.value = [
      {
        id: 1,
        name: '华为技术有限公司',
        category: '电子产品',
        contact: '张经理',
        phone: '0755-12345678',
        email: 'zhang@huawei.com',
        address: '深圳市龙岗区华为总部',
        status: 'active',
        createdAt: '2023-01-15 09:30:00',
        remark: '长期合作伙伴'
      },
      {
        id: 2,
        name: '阿里巴巴集团',
        category: '软件',
        contact: '李经理',
        phone: '0571-87654321',
        email: 'li@alibaba.com',
        address: '杭州市西湖区阿里巴巴园区',
        status: 'active',
        createdAt: '2023-03-22 14:15:30',
        remark: '优质供应商'
      },
      {
        id: 3,
        name: '小米科技有限公司',
        category: '电子产品',
        contact: '王经理',
        phone: '010-12345678',
        email: 'wang@xiaomi.com',
        address: '北京市海淀区小米科技园',
        status: 'suspended',
        createdAt: '2023-05-10 11:20:45',
        remark: '价格竞争激烈'
      }
    ]
    pagination.total = 30
    loading.value = false
  }, 500)
}

// 操作按钮
const handleAddSupplier = () => {
  dialogTitle.value = '新增供应商'
  isEdit.value = false
  resetSupplierForm()
  supplierDialogVisible.value = true
}

const handleImport = () => {
  console.log('导入供应商')
}

const handleExport = () => {
  console.log('导出供应商')
}

// 编辑供应商
const handleEdit = (row: Supplier) => {
  dialogTitle.value = '编辑供应商'
  isEdit.value = true
  Object.assign(supplierForm, row)
  supplierDialogVisible.value = true
}

// 查看供应商
const handleView = (row: Supplier) => {
  console.log('查看供应商:', row)
}

// 切换供应商状态
const handleToggleStatus = (row: Supplier) => {
  console.log('切换供应商状态:', row)
  loadSupplierList()
}

// 删除供应商
const handleDelete = (row: Supplier) => {
  console.log('删除供应商:', row)
}

// 重置表单
const resetSupplierForm = () => {
  supplierForm.id = 0
  supplierForm.name = ''
  supplierForm.category = ''
  supplierForm.contact = ''
  supplierForm.phone = ''
  supplierForm.email = ''
  supplierForm.address = ''
  supplierForm.remark = ''
}

// 确认供应商操作
const confirmSupplier = () => {
  console.log('确认供应商操作:', supplierForm)
  supplierDialogVisible.value = false
  loadSupplierList()
}

// 分页操作
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadSupplierList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadSupplierList()
}

// 生命周期
onMounted(() => {
  loadSupplierList()
})
</script>

<style scoped>
.procurement-suppliers {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.list-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.function-area {
  margin: 20px 0;
  border-radius: 8px;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  align-items: center;
  height: 100%;
}

.batch-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.batch-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .procurement-suppliers {
    padding: 10px;
  }
  
  .function-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .batch-btn {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>